import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/module/admin/user/entities/user.entity';
import { UserShopId } from 'src/module/admin/user_shop-id/entities/user_shop-id.entity';
import { ILike, Like, Repository } from 'typeorm';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>,
    @InjectRepository(UserShopId)
    private readonly userShopRepository: Repository<UserShopId>,
  ) {}
  // create(createUserDto: CreateUserDto) {
  //   return 'This action adds a new user';
  // }

  findAll() {
    return `This action returns all user`;
  }

  // 根据用户的ID获取他产生的订单
  async findOneUser(userId: number): Promise<User | any> {
    const res = await this.userRepository.findOne({
      select: [
        'id',
        'name',
        'primary_id',
        'nickname',
        'cover',
        'city',
        'province',
        'sex',
        'age',
        'phone',
        'role',
        'description',
        'account',
      ],
      where: { id: userId },
    });

    // 查询拥有多少订单和购物车拥有多少
    const order_cart_number = await this.userRepository.findOne({
      relations: ['order', 'cart'],
      where: { id: userId },
    });

    const result = {
      ...res,
      order_number: order_cart_number.order.length || 0,
      cart_number: order_cart_number.cart.length || 0,
    };

    return { userInfo: result || {} };
  }

  // 成为商家
  async becomeShop(userId, params) {
    await this.userRepository.update(userId, { role: 'shop' });
    const user = await this.userRepository.findOne({ where: { id: userId } });
    const userShop = new UserShopId();
    userShop.shopName = params.shopName;
    userShop.user = user;
    return await this.userShopRepository.save(userShop);
  }

  // 获取用户车辆信息
  async getCarInfo(userId) {
    const res = await this.userRepository.findOne({
      relations: ['car', 'car.photos'],
      where: { id: userId, isDelete: false },
    });
    return res?.car || [];
  }

  // 修改用户信息
  async upDateUser(userId, params) {
    const user = await this.userRepository.findOne({
      where: { id: userId, isDelete: false },
    });
    if (Object.keys(params).includes('account')) {
      const sum = Number(params.account) + Number(user.account);
      return await this.userRepository.update(userId, { account: sum });
    }
    return await this.userRepository.update(userId, params);
  }

  // 获取店铺列表
  async findShopList(userId) {
    const res = await this.userRepository.findOne({
      relations: ['shopId'],
      where: { id: userId, isDelete: false },
    });
    if (res.role != 'shop') {
      return {
        code: 901,
        success: false,
        message: '当前用户不是商户',
      };
    }

    return {
      code: 900,
      data: res.shopId || [],
      msg: 'success',
    };
  }

  // 获取该商家发布了的服务
  async getServicesList(userId, keywords: string) {
    const res = await this.userRepository.findOne({
      relations: ['publish_service_id'],
      where: { id: userId, isDelete: false },
    });

    const publicServices = [];

    for (let i = 0; i < res.publish_service_id.length; i++) {
      const shopNameInfo = await this.userShopRepository.findOne({
        where: {
          shopId: res.publish_service_id[i].shopNameId,
          shopName: ILike(`%${keywords}%`),
        },
      });
      if (shopNameInfo) {
        publicServices.push({
          ...res.publish_service_id[i],
          shopName: shopNameInfo.shopName,
        });
      }
    }

    if (res.role != 'shop') {
      return {
        code: 901,
        success: false,
        message: '当前用户不是商户',
      };
    }

    return {
      code: 900,
      data: publicServices || [],
      total: publicServices.length,
      msg: 'success',
    };
  }

  // 添加店铺
  async addShop(userId, params) {
    const user = await this.userRepository.findOne({
      where: { id: userId, isDelete: false },
    });
    const userShop = new UserShopId();
    userShop.shopName = params.shopName;
    userShop.user = user;

    return await this.userShopRepository.save(userShop);
  }

  // update(id: number, updateUserDto: UpdateUserDto) {
  //   return `This action updates a #${id} user`;
  // }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
